package com.addplus.townmall.server.scheduled.scheduletask;

import com.addplus.townmall.server.api.mapper.town.*;
import com.addplus.townmall.server.api.model.town.*;
import com.addplus.townmall.server.api.model.town.param.ShopProductStockManagerParam;
import com.addplus.townmall.server.api.service.queue.ShopProductFightManagerService;
import com.addplus.townmall.server.api.utils.DataUtils;
import com.addplus.townmall.server.api.utils.date.DateUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.*;
import java.util.Calendar;
import java.util.Date;
import java.util.List;


/**
 * 类名: FightOnlineStatusTask
 *
 * @author zhangjiehang
 * @version V1.0
 * @date 2018/11/8 2:57 PM
 * @description 类描述: 拼团商品状态更改定时器
 */
@Component
public class FightOnlineStatusTask {

    private Logger logger = LoggerFactory.getLogger(FightOnlineStatusTask.class);


    @Autowired
    CouponMapper couponMapper;


    @Autowired
    private ShopProductFightMapper shopProductFightMapper;

    @Autowired
    OrderItemsFightMapper orderItemsFightMapper;

    @Autowired
    TownOrderFightMapper townOrderFightMapper;
    @Autowired
    MemberIntegralMapper memberIntegralMapper;

    @Reference(check = false, async = true)
    private ShopProductFightManagerService shopProductFightManagerService;


    /**
     * 拼团商品上架超时任务
     */
    @Scheduled(cron = "0 */1 * * * ?")
    private void setFightNotOnline() throws Exception {
        logger.info("开始执行拼团商品上架超时任务");
        List<ShopProductFight> onlineShop = shopProductFightMapper.selectList(new QueryWrapper<ShopProductFight>()
                .eq("is_deleted", 0).eq("online_status", 1));
        onlineShop.stream().forEach(o -> {
            LocalDateTime onlineTime = o.getOnlineTime();
            if (!DataUtils.isEmptyObject(onlineTime)) {
                Integer groupTime = o.getGroupTime();// 拼团时间
                LocalDateTime overTime = onlineTime.plusHours(groupTime);// 结束时间
                if (overTime.isBefore(LocalDateTime.now())) { // 拼团结束时间大于当前时间
                    o.setOnlineStatus(0);// 设置为下架状态
                    shopProductFightMapper.updateById(o);
                    List<Integer> orderIds = orderItemsFightMapper.getOrderItemsFightByShopProductId(o.getId());
                    orderIds.stream().forEach(ob -> {
                        this.sendFightFailueMessage(ob);
                    });
                }
            }
        });
        logger.info("拼团商品上架超时任务结束");
    }

    /**
     * 拼团订单拼团超时任务
     */
    @Scheduled(cron = "0 */1 * * * ?")
    private void setOrderFightTimeOut() throws Exception {
        logger.info("拼团订单拼团超时任务开始");
        List<TownOrderFight> townOrderFights = townOrderFightMapper.selectList(new QueryWrapper<TownOrderFight>()
                .eq("order_status", 2).eq("parent_id", 0).eq("is_delete", 0).eq("is_group", 1));
        townOrderFights.stream().forEach(o -> {
            LocalDateTime nowDateTime = LocalDateTime.now();
            // 如果超时了
            if (nowDateTime.isAfter(DateUtils.dateToLocalDateTimeSecondZero(o.getFightLastTime()))) {
                Integer id = o.getId();
                this.sendFightFailueMessage(id);
                List<TownOrderFight> fightMemberOrders = townOrderFightMapper.selectList(new QueryWrapper<TownOrderFight>()
                        .eq("parent_id", id).eq("is_delete", 0));// 查询团员订单
                fightMemberOrders.stream().forEach(ob -> {
                    this.sendFightFailueMessage(ob.getId());
                });
            }
        });
        logger.info("拼团订单拼团超时任务结束");
    }


    private void sendFightFailueMessage(Integer orderId) {
        try {
            ShopProductStockManagerParam shopProductStockManagerParam = new ShopProductStockManagerParam();
            shopProductStockManagerParam.setType(3);
            shopProductStockManagerParam.setOrderId(orderId);
            shopProductFightManagerService.shopProductFightStockQueue(shopProductStockManagerParam);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
    }

    /**
     * 拼团订单未付款长时间未关闭的订单
     */
    @Scheduled(cron = "0 */1 * * * ?")
    private void setOrderFightPayTimeOut() throws Exception {
        logger.info("拼团订单未付款长时间未关闭的订单定时任务开始");
        QueryWrapper<TownOrderFight> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("order_status", 1);
        queryWrapper.eq("pay_status", 1);
        queryWrapper.eq("is_delete", 0);
        List<TownOrderFight> townOrders = townOrderFightMapper.selectList(queryWrapper);
        if (townOrders == null || townOrders.isEmpty()) {
            logger.info("拼团订单未付款长时间未关闭的订单，列表为空");
            return;
        } else {
            LocalDateTime localDateTimeNow = LocalDateTime.now().minusMinutes(30);
            LocalDateTime localDateTimeNowFormat = LocalDateTime.of(localDateTimeNow.toLocalDate(), LocalTime.of(localDateTimeNow.getHour(), localDateTimeNow.getMinute(), 0));
            townOrders.forEach(item -> {
                if (item.getGmtCreate() != null) {
                    Instant instant = item.getGmtCreate().toInstant();
                    ZoneId zoneId = ZoneId.systemDefault();
                    LocalDateTime localTimeOutDate = instant.atZone(zoneId).toLocalDateTime();
                    if (localTimeOutDate != null) {
                        if (localDateTimeNowFormat.isEqual(localTimeOutDate) || localDateTimeNowFormat.isAfter(localTimeOutDate)) {
                            UpdateWrapper<TownOrderFight> updateWrapper = new UpdateWrapper<>();
                            updateWrapper.eq("id", item.getId());
                            updateWrapper.set("order_status", 4);
                            updateWrapper.set("close_reason", "超时未付款，拼团失败");
                            updateWrapper.set("close_date", localDateTimeNow);
                            updateWrapper.set("gmt_modified", localDateTimeNow);
                            townOrderFightMapper.update(new TownOrderFight(), updateWrapper);
                        }
                    }
                }

            });
            logger.info("拼团订单未付款长时间未关闭的订单定时任务完成");
        }
    }

}
